﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace V32Assembler
{
    public class Macro
    {
        public string Name { get; private set; }
        public string[] ArgNames { get; private set; }
        public string[] Lines { get; private set; }

        public Macro(string name, string[] argNames, string[] lines)
        {
            Name = name;
            ArgNames = argNames;
            Lines = lines;

            List<string> args = new List<string>();
            foreach (string arg in ArgNames)
            {
                if (args.Contains(arg))
                    throw new Error("Macro '" + Name + "' has multiply defined argument: '" + arg + "'.");
                else args.Add(arg);
            }
        }

        public string[] Expand(params string[] args)
        {
            if (ArgNames.Length != args.Length)
                throw new Error("Macro '" + Name + "' requires " + ArgNames.Length + " argument"
                    + (ArgNames.Length == 1 ? "" : "s") + ".");

            foreach (string arg in args)
                foreach (string argName in ArgNames)
                    if (arg.Contains("<" + argName + ">"))
                        throw new Error("An argument to a macro must not contain text that would be expanded as an argument name by the macro expansion.");

            string[] replaced = Lines.ShallowCopy().ToArray();
            for (int i = 0; i < Lines.Length; i++)
                for (int arg = 0; arg < ArgNames.Length; arg++)
                    replaced[i] = replaced[i].Replace("<" + ArgNames[arg] + ">", args[arg]);

            return replaced;
        }
    }
}
